using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;
using Read.Models;
using Read.Utility;

namespace Read.Services
{
    public class AdminService : BaseService
    {
        /// <summary>
        /// 查询后台用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultData<List<AdminModel>> getAdminList(QueryParamsAdmin query)
        {
            using (var connection = GetConnection())
            {
                string countQuery = $"SELECT COUNT(1) FROM `{Tables.Admin}` AS A LEFT JOIN `{Tables.Role}` AS R ON A.RoleId = R.Id /**where**/";
                string sql = $"SELECT A.`Id`,A.`UserName`,A.`LastLoginTime`,A.`LastLoginIp`,A.`Email`,A.`Remark`,A.`CreateTime`,A.`UpdateTime`,A.`Status`,A.`RoleId`,R.`Name` AS RoleText FROM `{Tables.Admin}` AS A LEFT JOIN `{Tables.Role}` AS R ON A.RoleId = R.Id /**where**/ /**orderby**/ limit @PageIndex,@PageSize";
                string Role = query.RoleId == 0 ? string.Empty : query.RoleId.ToString();
                if (query.CreateTimeMin != null)
                {
                    string[] datestrs = query.CreateTimeMin.Split(new Char[] { '~' });
                    query.CreateTimeMin = Tools.ToUnixTime(Convert.ToDateTime(datestrs[0].Trim())).ToString();
                    query.CreateTimeMax = Tools.ToUnixTime(Convert.ToDateTime(datestrs[1].Trim())).ToString();
                }
                var currentPageIndex = (query.Index - 1) * query.Size;
                SqlBuilder builder = new SqlBuilder();

                var count = builder.AddTemplate(countQuery);
                var selector = builder.AddTemplate(sql, new { PageIndex = currentPageIndex, PageSize = query.Size });

                if (!string.IsNullOrEmpty(query.UserName))
                    builder.Where("A.UserName Like @UserName", new { UserName = "%" + query.UserName + "%" });

                if (!string.IsNullOrEmpty(query.Email))
                    builder.Where("A.Email Like @Email", new { Email = "%" + query.Email + "%" });

                if (!string.IsNullOrEmpty(Role))
                    builder.Where("A.RoleId Like @RoleId", new { RoleId = "%" + Role + "%" });

                if (!string.IsNullOrEmpty(query.CreateTimeMin))
                    builder.Where("A.CreateTime >= @CreateTimeMin", new { CreateTimeMin = query.CreateTimeMin });

                if (!string.IsNullOrEmpty(query.CreateTimeMax))
                    builder.Where("A.CreateTime < @CreateTimeMax", new { CreateTimeMax = query.CreateTimeMax });

                //排序
                builder.OrderBy("A.Id ASC");

                var totalRecords = connection.Query<int>(count.RawSql, count.Parameters).Single();
                var value = connection.Query<AdminModel>(selector.RawSql, selector.Parameters).ToList();
                var res = new ResultData<List<AdminModel>>()
                {
                    Result = true,
                    Total = totalRecords,
                    Data = value
                };
                return res;
            }
        }

        // /// <summary>
        // /// 查询后台用户列表
        // /// </summary>
        // /// <param name="query"></param>
        // /// <returns></returns>
        // public List<AdminModel> getadminlist2(QueryParamsAdmin query)
        // {

        //     var listRows = query.Size; // 列表每页显示行数
        //     var firstRow = (query.Index - 1) * listRows; // 起始行数
        //     var sql = getSQl(query);
        //     //分页查询
        //     var limit = " LIMIT @FirstRow,@ListRows";
        //     sql += limit;
        //     //var sql = $"SELECT * FROM `{Tables.Admin}` ORDER BY Id ASC LIMIT @FirstRow,@ListRows";
        //     //Console.WriteLine(sql);
        //     var adminlist = connection.Query<AdminModel>(sql, new { FirstRow = firstRow, ListRows = listRows }).ToList();
        //     return adminlist;
        // }

        // /// <summary>
        // /// 组合sql语句
        // /// </summary>
        // /// <param name="query"></param>
        // /// <returns></returns>
        // private string getSQl(QueryParamsAdmin query)
        // {
        //     string Role = query.RoleId == 0 ? string.Empty : query.RoleId.ToString();
        //     var where = "AND A.UserName LIKE '%" + query.UserName + "%' AND A.Email like '%" + query.Email + "%' AND A.RoleId like '%" + Role + "%'";
        //     if (query.CreateTimeMin != null)
        //     {
        //         string[] datestrs = query.CreateTimeMin.Split(new Char[] { '~' });
        //         query.CreateTimeMin = Tools.ToUnixTime(Convert.ToDateTime(datestrs[0].Trim())).ToString();
        //         query.CreateTimeMax = Tools.ToUnixTime(Convert.ToDateTime(datestrs[1].Trim())).ToString();
        //         string wheredata = " AND A.CreateTime>='" + query.CreateTimeMin + "' and A.CreateTime<'" + query.CreateTimeMax + "' ";
        //         where += wheredata;
        //     }
        //     var sql = $"SELECT A.`Id`,A.`UserName`,A.`LastLoginTime`,A.`LastLoginIp`,A.`Email`,A.`Remark`,A.`CreateTime`,A.`UpdateTime`,A.`Status`,A.`RoleId`,R.`Name` AS RoleText FROM `{Tables.Admin}` AS A LEFT JOIN `{Tables.Role}` AS R ON A.RoleId = R.Id WHERE 1=1 {where} ORDER BY A.Id ASC ";
        //     return sql;
        // }

        // /// <summary>
        // /// 查询当前查询的数据条数
        // /// </summary>
        // /// <returns></returns>
        // public int getadmincount(QueryParamsAdmin query)
        // {
        //     var sqlcount = getSQl(query);
        //     //var sql = $"SELECT count(Id) AS count FROM `{Tables.Admin}`";
        //     //Console.WriteLine(sql);
        //     var listcount = connection.Query<AdminModel>(sqlcount).ToList();
        //     return listcount.Count;
        // }

        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public long adminAdd(AdminModel model)
        {
            using (var connection = GetConnection())
            {
                if (string.IsNullOrEmpty(model.UserName))
                {
                    return 1;
                }
                //Console.WriteLine("++++++++++++++++++"+model.ToJson());
                model.BindAccount = "";
                model.CreateTime = Tools.ToUnixTime();
                //model.Email = "root2@xssc.cc";
                //model.Id:3
                model.LastLoginIp = "127.0.0.1";
                model.LastLoginTime = Tools.ToUnixTime();
                model.RoleText = "";
                model.Verify = Tools.RandomString(6);
                model.Password = Tools.HasPassword(model.Password, model.Verify);
                //model.Remark:"演示管理员"
                //model.RoleId:3
                //model.Status:1
                model.UpdateTime = Tools.ToUnixTime();
                //model.UserName:"xiongzhaoxu";

                return connection.Insert(model);
            }
        }

        /// <summary>
        /// 根据Id查询用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AdminModel getAdminById(int id)
        {
            using (var connection = GetConnection())
            {
                var sql = $"SELECT * FROM `{Tables.Admin}` WHERE Id=@Id";
                return connection.QueryFirst<AdminModel>(sql, new { Id = id });
            }
        }

        /// <summary>
        /// 用户编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool adminEdit(AdminModel model)
        {
            using (var connection = GetConnection())
            {
                AdminModel admin = getAdminById(model.Id);
                //Console.WriteLine("++++++++++++++++++" + model.ToJson());
                model.BindAccount = "";
                model.CreateTime = admin.CreateTime;
                //model.Email = "root2@xssc.cc";
                //model.Id:3
                model.LastLoginIp = admin.LastLoginIp;
                model.LastLoginTime = admin.LastLoginTime;
                model.RoleText = "";
                //if (model.Password != null)
                if (model.Password != null && model.Password.Length != 0)
                {
                    model.Verify = Tools.RandomString(6);
                    model.Password = Tools.HasPassword(model.Password, model.Verify);
                }
                else
                {
                    model.Verify = admin.Verify;
                    model.Password = admin.Password;
                }
                //model.Remark:"演示管理员"
                //model.RoleId:3
                //model.Status:1
                model.UpdateTime = Tools.ToUnixTime();
                model.UserName = admin.UserName;

                return connection.Update(model);
            }
        }

        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool adminDel(int id)
        {
            using (var connection = GetConnection())
            {
                //AdminModel admin = getAdminById(id);
                //Console.WriteLine(admin.ToJson());
                //return true;
                //return connection.Delete(admin);
                return connection.Delete(new AdminModel() { Id = id });
            }
        }
    }
}